package org.cpar.compiler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;

public class Main {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws Exception {

		File tempBat = File.createTempFile("cpar-batch-build", ".bat");

		BufferedWriter writer = new BufferedWriter(new FileWriter(tempBat));
		writer.write("call \"C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\VC\\bin\\amd64\\vcvars64.bat\"\n"
				+ "@echo on\n"
				+ "cl.exe %1 /I%CPAR_INCLUDES% rt.lib /link /LIBPATH:%CPAR_LIBS% /out:%2 /NODEFAULTLIB:MSVCRT");
		writer.flush();
		writer.close();

		ArrayList<String> toCompile = new ArrayList<String>();

		for (String arg : args) {
			File fi = new File(arg);

			toCompile.clear();

			if (fi.isDirectory()) {
				File[] files = fi.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File file, String name) {
						return name.endsWith(".cpar");
					}
				});

				for (File f : files) {
					toCompile.add(f.getAbsolutePath());
				}

			} else {
				toCompile.add(arg);
			}

			for (String a : toCompile) {

				System.out.print("COMPILANDO " + a);
				FileInputStream fis = new FileInputStream(a);
				FileOutputStream fos = new FileOutputStream(a + ".c");

				try {
					CPARCompiler.compile(fis, fos);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				} finally {
					fis.close();
					fos.close();
				}

				String name = a.substring(0, a.length() - "cpar".length());
				name = name + "exe";
				String command = "cmd /c " + tempBat.getAbsolutePath() + " \""
						+ a + ".c\" \"" + name + "\"";

				try {
					Process proc = Runtime.getRuntime().exec(command);

					System.out.println(command);
					BufferedReader stdInput = new BufferedReader(
							new InputStreamReader(proc.getInputStream()));

					String s;
					StringWriter w = new StringWriter();
					while ((s = stdInput.readLine()) != null) {
						w.write(s);
						w.write('\n');
					}

					if (proc.waitFor() != 0) {
						System.out.println("=== VSTUDIO ERROR ===");
						System.out.print(w);
						System.out.println();
					}else
						System.out.println("SUCESSO");
					
					w.close();

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}

			}
		}
	}
}
